package com.jd.jstable.strategy.route;

import com.jd.jstable.config.KeyMode;
import com.jd.jstable.strategy.Strategy;
import com.jd.jstable.utils.ReflectionUtil;
import com.jd.jstable.utils.SpringContextHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 函数级别的路由
 * Created by chenyipu on 2018/1/22.
 */
@Service("MD5_138cc4666fbd6262a0a57cab833c5dbc_route")
public class RouteStrategy extends Strategy{

    private static final Log logger = LogFactory.getLog(RouteStrategy.class);

    @Resource
    ParameterConvertor parameterConvertor;

    @Override
    public Object solve(Object invoker, Method method, Object[] args, String param, KeyMode keyMode) {
        try {
            String[] params = param.split("@");
            String left, right= null;
            if (params.length == 2 ) {
                left = params[0];
                right = params[1];
            }else if (params.length == 1 ) {
                left = params[0];
            }else {
                logger.error("_route is configured in wrong format.");
                return null;
            }
            //true invoker and method
            String[] routeTargets = left.split("\\.");
            //get invoker bean and find method
            Object routeInvoker = SpringContextHolder.getBean(routeTargets[0]);
            Method routeMethod = ReflectionUtil.findMethodByName(routeInvoker.getClass(), routeTargets[1]);
            //try find router args
            Object[] routeArgs = parameterConvertor.convert(args, routeMethod.getParameterCount(),  right);
            //FIXME Return
            return routeMethod.invoke(routeInvoker, routeArgs);
        }catch (Exception e){
            logger.error("Route Strategy Exception:", e);
            return null;
        }
    }
}
